<template>
    <div class="InboundList-box">
       <!-- 活动列表 -->
        <!-- 测试 -->
        <h3 class="mb16">活动列表</h3>
        <!-- 搜索栏 -->
        <serchForm :Form="inventoryForm" :FormLabel="inventoryFormLabel" @onSearch="onSearch" />
        <!-- 增删改查 -->
        <div class="function-box" v-if="checkPermi(['system:inventory:edit'])">
                <el-button class="addBtn2" @click="add">新增</el-button>
                <el-button class="delBtn2">删除</el-button>
        </div>
        <!-- 活动列表页面 -->
    <forTableCom
      :color="color"
      :idActive="idActive"
      :bg="bg"
      :total="total"
      :page="pageNum"
      :limit="pageSize"
      @handleSelectionChange="handleSelectionChange"
      @handleChange="handleChange"
      @updatePage="updatePage"
      @updateLimit="updateLimit"
      :tableHeaderData="inventoryTableHeaderData"
      :tableData="inventoryTableData"
      :activityListsShow='activityListsShow'
      @activityListsView="activityListsView"
      @activityListsEdit="activityListsEdit"
      :pagination="inventoryTableData.length>0"
    >
    </forTableCom>
    <!-- 添加或修改用户配置对话框 -->
      <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
         <el-form :model="form" :rules="rules" label-position="top" ref="userRef" label-width="80px">
            <div class="formItembox">
                  <el-form-item class="formItem" label="活动名称" prop="title">
                     <el-input  v-model="form.title" placeholder="请输入活动名称" maxlength="11" />
                  </el-form-item>
                  <el-form-item class="formItem" label="报名开始时间" prop="signupStart">
                     <el-date-picker
                       class="input"
                         v-model="form.signupStart"
                         type="datetime"
                         placeholder="请选择报名开始时间"
                       />
                  </el-form-item>
                  <el-form-item class="formItem" label="报名截止时间" prop="signupEnd">
                     <el-date-picker
                       class="input"
                         v-model="form.signupEnd"
                         type="datetime"
                         placeholder="请选择报名截止时间"
                       />
                  </el-form-item>
                  <el-form-item class="formItem" label="活动开始时间" prop="activityStart">
                     <el-date-picker
                       class="input"
                         v-model="form.activityStart"
                         type="datetime"
                         placeholder="选择活动开始时间"
                       />
                  </el-form-item>
                  <el-form-item class="formItem" label="活动结束时间" prop="activityEnd">
                     <el-date-picker
                       class="input"
                         v-model="form.activityEnd"
                         type="date"
                         placeholder="选择活动结束时间"
                       />
                  </el-form-item>
                  <el-form-item class="formItem" label="活动地点" prop="address">
                     <el-input  v-model="form.address" placeholder="请输入活动地点" maxlength="11" />
                  </el-form-item>
                  <el-form-item class="formItem" label="活动范围" prop="activityScopeList">
                     <!-- 活动范围 -->
                     <el-tree-select
                         ref="treeRef"
                         v-model="form.activityScopeList"
                         :data="genderOptions"
                         :props="{ value: 'id', label: 'label', children: 'children' }"
                         check-strictly
                         placeholder="请选择活动范围"
                         node-key="id"
                         multiple
                         filterable
                     />
                  </el-form-item>
                  <el-form-item class="formItem" label="得分标准" prop="scoreType">
                     <el-select v-model="form.scoreType" placeholder="请选择得分标准">
                        <el-option label="参与得分" value="1">参与得分</el-option>
                        <el-option label="指标评分" value="2">指标评分</el-option>
                        <el-option label="区间得分" value="3">区间得分</el-option>
                     </el-select>
                  </el-form-item>
                  <el-form-item class="formItem" label="活动类型" prop="activityCategoryId">
                     <el-select v-model="form.activityCategoryId" placeholder="请选择活动类型">
                        <el-option
                           v-for="item in activityTypes"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value"
                        ></el-option>
                     </el-select>
                  </el-form-item>
                   <el-form-item class="formItem" label="状态">
                      <el-radio-group v-model="form.isOpen">
                         <el-radio label="0" value="0">开启</el-radio>
                         <el-radio label="1" value="1">关闭</el-radio>
                      </el-radio-group>
                   </el-form-item>          
                  <el-form-item class="formItem" label="活动内容">
                     <el-input v-model="form.content" type="textarea" placeholder="请输入内容"></el-input>
                  </el-form-item>
            </div>
         </el-form>
         <!-- 上传图片 -->
          <p class="uploadTitle">上传文件</p>
          <FileUploads
                  :fileType="['']"
                  :limit="1"
                  :key="nodekey"
                  :fileSize="10"
                  :urlShow="urlShow"
                  @update:modelValue="handlerModelValue"
                  @size="size"
                  ></FileUploads>
         <template #footer>
            <div class="dialog-footer">
               <el-button @click="cancel">重置</el-button> 
               <el-button type="primary" @click="submitForm">提交</el-button>
            </div>
         </template>
      </el-dialog>

      <!-- 预览 -->
    <el-dialog v-model="dialogVisible" title="预览"  @closed="pauseVideo">

      <!-- pdf线上地址预览 -->
      <vue-pdf-embed 
      v-if="wenjianType==='.pdf' "
      :source="pdfUrl" 
      style="border: 1px solid #ddd; margin-top: 20px"
    />
    
    <!-- xlsx线上地址预览 -->
    <div v-if="wenjianType==='.xlsx' || wenjianType==='.xls' ">
    <div>
      <table border class="excel-table">
        <thead>
          <tr>
            <th v-for="(header, index) in headers" :key="index">{{ header }}</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(row, rowIndex) in sheetData" :key="rowIndex">
            <td v-for="(cell, cellIndex) in row" :key="cellIndex">{{ cell }}</td>
          </tr>
        </tbody>
      </table>
    </div>
    </div>
    <!-- 预览docx文件 -->
    <div v-if="wenjianType==='.docx' " ref="docxContainer" class="docx-preview"></div>
    <!-- 视频预览 -->
    <div v-if="wenjianType==='.mp4' || wenjianType==='.webm' || wenjianType==='.ogg' " class="video-wrapper">
        <video
          ref="videoPlayer"
          controls
          controlsList="nodownload"
          class="video-element"
        >
          <source :src="videoUrl" :type="videoType">
          您的浏览器不支持 HTML5 视频标签。
        </video>
    </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 图片线上地址预览 -->
    <div v-if="showPreview" class="preview-modal" @click.self="closePreview">
      <div class="preview-content">
        <img :src="currentImage" class="preview-image" />
        <button class="close-button" @click="closePreview">
          <svg viewBox="0 0 24 24" width="24" height="24">
            <path fill="currentColor" d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
          </svg>
        </button>
      </div>
    </div>

    </div>
</template>

<script setup>
import { ref, reactive, toRefs,computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import serchForm from '@/components/inventory/serchForm.vue'
import { checkPermi } from '@/utils/permission.js'
import forTableCom from '@/components/forTableCom/index.vue'
import { ElMessage,ElMessageBox } from 'element-plus'
import {delUser,addUser} from '@/api/system/upload.js'
import {quickCodeChildrenApi} from '@/api/system/dict/type.js'
import { getToken } from "@/utils/auth";
import FileUploads from './components/uploads.vue'
import VuePdfEmbed from 'vue-pdf-embed';
import * as XLSX from 'xlsx';
import { renderAsync } from 'docx-preview';
import {activityLists,activityListAddApi,activityDetail,activityPutApi} from '@/api/activityClassify/activityList.js'
import {getdeptApi} from '@/api/system/notice.js'
import {listUser} from '@/api/activityClassify/activityClassifyType.js'
import dayjs from 'dayjs';

const router = useRouter();
const route = useRoute();
const data = reactive({});
const { proxy } = getCurrentInstance();
let nodekey = ref(Math.random())

const title = ref("");
const open = ref(false);
const form = ref({
     title:'', //活动名称
     signupStart:'', //报名开始时间
     signupEnd:'', //报名截止时间
     activityStart:'', //活动开始时间
     activityEnd:'', //活动结束时间
     address:'', //活动地点
     activityScopeList:'', //活动范围
     scoreType:'', //得分标准
     activityCategoryId:'', //活动类型
     coverImageUrl:'',      //活动封面
     attachment:'',
     content:'',     //活动内容
     type:1,       //区分教师和学生
     isOpen:'0',     //状态
  })
/** 重置操作表单 */
function reset() {
  form.value = {
     title:undefined, //活动名称
     signupStart:undefined, //报名开始时间
     signupEnd:undefined, //报名截止时间
     activityStart:undefined, //活动开始时间
     activityEnd:undefined, //活动结束时间
     address:undefined, //活动地点
     activityScopeList:undefined, //活动范围
     scoreType:undefined, //得分标准
     activityCategoryId:undefined, //活动类型
     coverImageUrl:undefined,      //活动封面
     attachment:undefined, //
     content:undefined,     //活动内容
     type:1,       //区分教师和学生
     isOpen:'0',
  };
  proxy.resetForm("userRef");
};
const rules = ref({
    // name: [{ required: true, message: "请输入资料名称", trigger: "blur" }],
    // fileUrl: [{ required: true, message: "用户昵称不能为空", trigger: "blur" }],
    // categoryCode: [{ required: true, message: "请选择资料类型", trigger: "change"}],
  })

// 表单
let inventoryForm = ref({
  productCode:'',//活动类型
  uploadDate: '', // 活动时间
  name: '', // 活动名称
  id: '', // 活动编号
})
// 表单数据标题
let inventoryFormLabel = ref([
  {
    name: 'uploadDate',
    label: '活动时间',
    type: 'datetimerange',
  },
  {
    name: 'id',
    label: '活动编号',
  },
  {
    name: 'name',
    label: '活动名称',
  },
  {
    name: 'productCode',
    label: '活动类型',
  },
])
// 查找
const onSearch = (v) => {
  console.log(v,'查看入库页面时间参数')
  // 每次查询后回到页1
  pageNum.value = 1
}

// 显示操作栏
const activityListsShow = ref(true)
let idActive = 'id'
// 表格
let color = ref('#333')
let bg = ref('#d9d9d93b')
// 总条目数   pageSize 加 1
let total = ref(50)
// 当前页数
let pageNum = ref(1)
// 条数
let pageSize = ref(50)
// 存储勾选框的对象
let multipleSelection = ref([])
// 选中的列
const handleSelectionChange = (v) => {
  multipleSelection.value = v
  console.log(v,'打印v')
}
// 分页器大小  当前分页器
const handleChange = (v) => {
  let { page, limit } = v.page
  pageNum.value = page
  pageSize.value = limit
  // let params = inventoryForm.value
  // listUser(params)
}
// 当前页面位置发生变化
const updatePage = (v) => {
  console.log(v)
}
// 条目个数发生变化
const updateLimit = (v) => {
  console.log(v)
}
// 表格表头数据
let inventoryTableHeaderData = ref([
  {
    prop: 'id',
    label: '活动编号',
    sortable: true
  },
  {
    prop: 'coverImageUrl',
    label: '活动封面',
    coverImageUrlShow:true
  },
  {
    prop: 'title',
    label: '活动名称',
  },
  {
    prop: 'activityCategoryName',
    label: '活动类型',
  },
  {
    prop: 'signup',
    label: '报名时间',
    sortable: true,
    signupActivityShow:true
  },
  {
    prop: 'activityTime',
    label: '活动时间',
    activityTimeShow:true
  },
  {
    prop: 'activityScopeNameList',
    label: '活动范围',
    activityScopeNameListShow:true
  },
  {
    prop: 'scoreType',
    label: '得分标准',
    scoreTypeActivityShow:true
  },
  {
    prop: 'status',
    label: '状态',
    statusActivityShow:true
  },
  {
    prop: 'activityParticipationList',
    label: '已报名人数',
    activityPersonListShow:true
  },
])
// 表格数据内容
let inventoryTableData = ref([])
// const activityListsDel = (val)=>{  //列表单个删除操作
//       let {i , v} = val
//       console.log(v.id);
      
//       ElMessageBox.confirm(
//     '确定要删除该数据吗?',
//     '删除',
//     {
//       confirmButtonText: '确定',
//       cancelButtonText: '取消',
//       type: 'warning',
//     }
//   )
//     .then(async() => {
//         //  delUser(v.id).then(res=>{
//         //       if(res.code===200){
//         //            ElMessage({
//         //          message: '删除成功',
//         //          type: 'success',
//         //        })
//         //        listUserApiFn()
//         //       }
//         //  })
//     })
//     .catch(() => {
//       ElMessage({
//         type: 'info',
//         message: '已取消',
//       })
//     })
// }

const activityListsView = (val)=>{ //查看按钮
    let {i , v} = val
    router.push({path:`/activityListsDetail/${v.id}`})
}

let urlShow = ref('')
const activityListsEdit = (val)=>{ //编辑按钮
    let {i , v} = val
    editId.value = v.id
    console.log(val,'编辑活动');
    open.value = true
    title.value = '编辑活动'
    activityDetail(v.id).then(res=>{
        console.log(res,'打印详情数据');
        if(res.code===200){
             form.value.title = res.data.title
             form.value.signupStart = res.data.signupStart
             form.value.signupEnd = res.data.signupEnd
             form.value.activityStart = res.data.activityStart
             form.value.activityEnd = res.data.activityEnd
             form.value.address = res.data.address
             form.value.scoreType = String(res.data.scoreType)
             form.value.activityCategoryId = res.data.activityCategoryId
             form.value.content = res.data.content
            //  form.value.activityScopeList = res.data.activityScopeNameList
             form.value.activityScopeList = res.data.activityScopeList
             nodekey.value = Math.random()
             urlShow.value = res.data.coverImageUrl
             form.value.isOpen = String(res.data.isOpen)

        }
    })
}

const editId = ref(-1)
const add = ()=>{ //打开新增弹出框
    reset()
    open.value = true
    title.value = '新增活动'
    editId.value=-1
    urlShow.value=undefined
    nodekey.value = Math.random()
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["userRef"].validate(valid => {
    if (valid) {
      console.log(form.value,'form.value');
      
      if(editId.value===-1){
            form.value.activityStart = dayjs(form.value.activityStart).format('YYYY-MM-DD HH:mm:ss'),
            form.value.activityEnd = dayjs(form.value.activityEnd).format('YYYY-MM-DD HH:mm:ss'),
            form.value.signupStart = dayjs(form.value.signupStart).format('YYYY-MM-DD HH:mm:ss'),
            form.value.signupEnd = dayjs(form.value.signupEnd).format('YYYY-MM-DD HH:mm:ss'),
            // delete form.value.fileUrl
             activityListAddApi(form.value).then(res=>{
                 if(res.code===200){
                    ElMessage({
                       message: '添加成功',
                       type: 'success',
                     })
                     open.value = false
                    activityListsFn()
                 }
             })
      }else{
            form.value.activityStart = dayjs(form.value.activityStart).format('YYYY-MM-DD HH:mm:ss'),
            form.value.activityEnd = dayjs(form.value.activityEnd).format('YYYY-MM-DD HH:mm:ss'),
            form.value.signupStart = dayjs(form.value.signupStart).format('YYYY-MM-DD HH:mm:ss'),
            form.value.signupEnd = dayjs(form.value.signupEnd).format('YYYY-MM-DD HH:mm:ss'),
            form.value.id = editId.value
             activityPutApi(form.value).then(res=>{
                if(res.code===200){
                    ElMessage({
                       message: '编辑成功',
                       type: 'success',
                     })
                     open.value = false
                     activityListsFn()
                 }
             })
      }
      
    }
  });
};
const cancel = ()=>{  //重置
     reset()
}
// 查询活动列表数据
const activityListsFn = async (data = '') => {
  let page = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    type:1
  }
  let params = Object.assign(data, page)
  let res = await activityLists(params)
  let { code, rows } = res
  if (code == 200) {
    total.value = res.total
    inventoryTableData.value = rows
    console.log(rows,'打印活动列表数据');

    // 使用 map 转换 attachment，同时保留其他字段
    // inventoryTableData.value = rows.map(item => ({
    //   ...item, // 保留所有原有字段
    //   attachment: JSON.parse(item.attachment)[0] // 覆盖 attachment 为解析后的字符串
    // }));
  }
}
let options = ref([])
const quickCodeChildrenApiFn =()=>{  //通过快码获得资料类型
    quickCodeChildrenApi({parentCode:30000}).then(res=>{
        console.log(res,'查询子集快码');
        if(res.code===200){
           options.value = res.rows
        }
    })
}

// 获取活动范围下拉信息
const genderOptions = ref([])
const getdeptApiFn = async () => {
  let page = {
    pageNum: 1,
    pageSize: -1,
  }
  let {code, data} = await getdeptApi(page)
  if (code === 200) {
    genderOptions.value = data
  }
}
// 获取活动类型下拉信息
const activityTypes = ref([])
const listUserFn = async () => {
  let page = {
    pageNum: 1,
    pageSize: -1,
  }
  let {code, rows} = await listUser(page)
  if (code === 200) {
    activityTypes.value = rows
    let rowList = []
  rows.forEach((v) => {
    rowList.push({
      value: v.id,
      label: v.name,
    })
  })
  activityTypes.value = rowList
  }
}

// 图片上传
// 获取的图片
let urlList = ref([])
const handlerModelValue = (v) => {
       form.value.coverImageUrl = v


      //数组写法
      // urlList.value = v.map(item => item.url);  //过滤id
      // form.value.attachment = JSON.stringify(urlList.value)
      // console.log(form.value.attachment,'上传的图片地址');

  // var index = v.lastIndexOf("."); //用于返回指定字符串在当前字符串中最后一次出现的位置。
  // var name = v.slice(index); //目的用来截取.jpg等字段
  // form.value.fileType = name.replace(".", "");
  
}
const size = (val)=>{
     console.log(val,'文件大小');
    //  form.value.fileSize = val
}

//预览功能
const dialogVisible = ref(false)
const wenjianType = ref('')
const sheetData = ref([]);
const headers = ref([]);
const pdfUrl = ref(''); 
const showPreview = ref(false);
const currentImage = ref('');

const docxContainer = ref(null);

const videoPlayer = ref(null);
const videoUrl = ref('')
const videoUrlType = ref('')
const videoType = computed(() => {  //播放视频
  const ext = videoUrlType.value.split('.').pop().toLowerCase();
  switch(ext) {
    case 'mp4': return 'video/mp4';
    case 'webm': return 'video/webm';
    case 'ogg': return 'video/ogg';
    default: return 'video/mp4';
  }
});
const pauseVideo = () => { //关闭视频
  if (videoPlayer.value) {
    videoPlayer.value.pause();
    videoPlayer.value.currentTime = 0;
  }
};

// 关闭预览
const closePreview = () => {
  showPreview.value = false;
  document.body.style.overflow = '';
};
// 点击ESC键关闭预览
const handleKeyDown = (e) => {
  if (e.key === 'Escape' && showPreview.value) {
    closePreview();
  }
};
// 添加键盘事件监听
window.addEventListener('keydown', handleKeyDown);
onMounted(()=>{
    Promise.all([activityListsFn(),quickCodeChildrenApiFn(),getdeptApiFn(),listUserFn()])
})

</script>

<style lang='scss' scoped>
.InboundList-box {
    padding: 16px;
    .function-box {
    display: flex;
    align-items: center;
  }
}
.dialog-footer {
  display: flex;
  justify-content: center; /* 水平居中 */
}
.formItembox {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;
      // justify-content: center;
      box-sizing: border-box;

      .formItem {
        width: 30%;
        // margin-right: 30px;
      }
      .formItem:last-child {
        width: 100%;
        margin-right:0;
      }
      .formItem:nth-child(3) {
        margin-right:0;
      }
    }
:deep(.el-select .el-input__wrapper) {  //下拉框
  width: 240px;
}
:deep(.el-date-editor){  //日期选择器
   width: 240px;
}
.formItem :deep(.el-input) {  //input输入框
  width: 240px;
}
:deep(.el-textarea__inner){   //文本域
    height: 80px;
}


.excel-table{
   border: 1px solid rgb(0, 0, 0);
        border-image: none;
        width: 100%;
        text-align: center;
        border-collapse: collapse;
        background-color: rgb(255, 255, 255);
}
:deep(.el-form-item:nth-child(4) .el-form-item__label) {
  margin-left: 0;
}

//图片预览样式
.preview-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.preview-content {
  position: relative;
  max-width: 90%;
  max-height: 90%;
}

.preview-image {
  max-width: 100%;
  max-height: 90vh;
  object-fit: contain;
  border-radius: 4px;
}

.close-button {
  position: absolute;
  top: -40px;
  right: -40px;
  background: none;
  border: none;
  color: white;
  cursor: pointer;
  font-size: 24px;
  padding: 10px;
  transition: transform 0.2s;
}

.close-button:hover {
  transform: scale(1.2);
}

@media (max-width: 768px) {
  .close-button {
    top: -50px;
    right: 10px;
  }
}
//docx预览
.docx-preview {
  overflow: auto;
  border: 1px solid #eee;
}
:deep(.docx-wrapper) {
  padding: 0;
  background: #fff;
}

//视频预览
.video-wrapper {
  position: relative;
  padding-bottom: 56.25%; /* 16:9 比例 */
  height: 0;
  overflow: hidden;
}

.video-element {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #000;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .video-thumbnail {
    max-width: 100%;
  }
}
.uploadTitle{
  font-weight: 600;
}
</style>
